import logging
from logging import debug
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)

import numpy as np

#from dateutil import parser
from matplotlib.dates import date2num
import datetime

def _make_mkdate(time_format):
    """ Used to generate a function which is fast at parsing dates """
    year = time_format[0]
    month = time_format[1]
    day = time_format[2]
    hour = time_format[3]
    minute = time_format[4]
    second = time_format[5]
    micro_second = time_format[6]
    if len(second) != 2:
        return lambda s: date2num(datetime.datetime(int(s[year[0]:year[1]]),
                                                int(s[month[0]:month[1]]),
                                                int(s[day[0]:day[1]]),
                                                int(s[hour[0]:hour[1]]),
                                                int(s[minute[0]:minute[1]])))
    elif len(micro_second) != 2:
        return lambda s: date2num(datetime.datetime(int(s[year[0]:year[1]]),
                                                int(s[month[0]:month[1]]),
                                                int(s[day[0]:day[1]]),
                                                int(s[hour[0]:hour[1]]),
                                                int(s[minute[0]:minute[1]]),
                                                int(s[second[0]:second[1]])))
    else:
        return lambda s: (datetime.datetime(int(s[year[0]:year[1]]),
                                                int(s[month[0]:month[1]]),
                                                int(s[day[0]:day[1]]),
                                                int(s[hour[0]:hour[1]]),
                                                int(s[minute[0]:minute[1]]),
                                                int(s[second[0]:second[1]]),
                                                1000 * int(s[micro_second[0]:micro_second[1]]))
                                                - datetime.datetime(1970, 1, 1)).total_seconds()

    # The slow alternative should not be used
    #return date2num(parser.parse(s, yearfirst=True, dayfirst=False))

def _find_converters(para_describs, time_format):
    dtyp = []
    time_idxs = []
    for i, para in enumerate(para_describs):
        para_short = para[0:4]
        if "Stri" == para_short:
            dtyp.append('|O4')
        elif "Floa" == para_short:
            dtyp.append(float)
        elif "Time" == para_short:
            dtyp.append(float)
            time_idxs.append(i)
        else:
            logging.warning("Unknown type")
            dtyp.append(float)
    debug("Found" + str(len(time_idxs)) + " time indexes")
    convs = dict((idx, _make_mkdate(time_format)) for idx in time_idxs)
    return dtyp, convs

def read_csv_file(filename, para_names, para_describs, delim, time_format, header=2):
    dtyp, convs = _find_converters(para_describs, time_format)
    data = np.genfromtxt(filename,
                         delimiter=delim,
                         names=para_names,
                         skip_header=header,
                         converters=convs,
                         dtype=dtyp)
    return data
